package com.atguigu.gmall.activity.consumer;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.activity.mapper.SecKillMapper;
import com.atguigu.gmall.common.config.RabbitService;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.SeckillOrder;
import com.atguigu.gmall.model.activity.UserRecode;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 监听用户下单排队的监听类
 */
@Component
public class seckillOrderAddConsumer {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RabbitService rabbitService;

    @Autowired
    SecKillMapper secKillMapper;

    @RabbitListener(queues = "seckill_queue")
    public void addOrder(String message){
        //将接收的消息类型转换为userRecord
        UserRecode userRecode = JSONObject.parseObject(message,UserRecode.class);
        //校验商品信息
        String time = userRecode.getTime();
        String goodsId = userRecode.getGoodsId();
        SeckillGoods goods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_" + time).get(goodsId);
        //如果商品存在则从redis商品队列中取出一个商品
        Object o = redisTemplate.boundListOps("seckillGoodsQueue_" + goodsId).leftPop();
        //判断队列中剩余库存信息
        if (o != null){
            //库存足够则创建订单信息
            SeckillOrder seckillOrder = new SeckillOrder();
            //生成主键
            UUID.randomUUID().toString().replaceAll("_","");
            //填充商品信息
            seckillOrder.setGoodsId(goodsId);
            //填充数量信息
            seckillOrder.setNum(userRecode.getNum());
            //填充金额
            seckillOrder.setMoney(userRecode.getNum()*goods.getPrice().doubleValue()+"");
            //填充用户信息
            seckillOrder.setUserId(userRecode.getUsername());
            //插入创建时间
            seckillOrder.setCreateTime(userRecode.getCreateTime());
            //插入订单状态
            seckillOrder.setStatus("0");
            //将订单信息存入redis
            redisTemplate.boundHashOps("SeckillOrder_"+userRecode.getUsername()).put(seckillOrder.getId(),seckillOrder);
            //更新redis中库存
            Long stockNum = redisTemplate.boundHashOps("SeckillGoodsStockNum").increment(goodsId, -1);
            //获取跟新完成后的数量
            goods.setStockCount(stockNum.intValue());
            //判断剩余库存是否足够
            if(stockNum > 0){
                //库存足够更新库存
                redisTemplate.boundHashOps("SeckillGoods_" + time).put(goodsId,goods);
            }else {
                //库存不够时回滚库存
                redisTemplate.boundHashOps("SeckillGoods_" + time).delete(goodsId);
                //将数据保存到数据库
                secKillMapper.updateById(goods);
            }
            //更新排队状态
            userRecode.setStatus(2);
            //补充排队参数信息
            userRecode.setMoney(Float.valueOf(seckillOrder.getMoney()));
            userRecode.setOrderId(seckillOrder.getId());
            //将新信息更新到redis
            redisTemplate.boundValueOps("SeckillStatus_"+userRecode.getUsername()).set(userRecode);
            //发送一个延迟消息
            rabbitService.sendMessage("seckill_dead_exchange","seckill.dead.order",JSONObject.toJSON(seckillOrder),"");
            return;
        }
        //商品库存不足，更改排队状态，下单失败
        userRecode.setStatus(3);
        redisTemplate.boundValueOps("SeckillStatus_"+userRecode.getUsername()).set(userRecode);
        redisTemplate.delete("SeckillUserQueue_"+userRecode.getUsername());
    }
}
